package com.yun.zf.admin.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lowagie.text.DocumentException;
import com.yun.zf.admin.mapper.ZfPactMapper;
import com.yun.zf.admin.service.*;
import com.yun.zf.admin.util.PDFUtil;
import com.yun.zf.common.admin.domain.ZfOrder;
import com.yun.zf.common.admin.domain.ZfPactPdf;
import com.yun.zf.common.admin.domain.ZfPactPersonInfo;
import com.yun.zf.common.admin.dto.house.PactHouseDto;
import com.yun.zf.common.admin.dto.pact.PactDetailDto;
import com.yun.zf.common.admin.dto.pact.PactPersonDto;
import com.yun.zf.common.admin.dto.pact.PactSearchResMo;
import com.yun.zf.common.admin.model.pact.*;
import com.yun.zf.common.app.domain.ZfPact;
import com.yun.zf.common.constant.Constants;
import com.yun.zf.common.constant.PactConstants;
import com.yun.zf.common.mapstruct.admin.PactMapper;
import com.yun.zf.system.security.utils.SecurityUtils;
import com.yun.zf.system.utils.AliyunOssUtil;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 合同表 服务实现类
 * </p>
 *
 * @author cj
 * @since 2021-04-07
 */
@Service
@Slf4j
public class ZfPactServiceImpl extends ServiceImpl<ZfPactMapper, ZfPact> implements ZfPactService {
    @Autowired
    private ZfPactPersonInfoService personInfoService;
    @Autowired
    private ZfPactRentInfoService rentInfoService;
    @Autowired
    private ZfOrderService orderService;
    @Autowired
    private ZfCustomerService customerService;
    @Autowired
    private ZfHouseBasicService basicService;
    @Autowired
    private ZfOwnerCertificateService ownerCertificateService;
    @Autowired
    private ZfPactPersonInfoService infoService;
    @Autowired
    private ZfPactRentInfoService pactRentInfoService;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    private PDFUtil pdfUtil;
    @Autowired
    private AliyunOssUtil ossUtil;
    @Autowired
    private ZfPactPdfService pdfService;
    // 文件路径
    @Value("${pact.upload}")
    private String upload;

    @Override
    @Transactional
    public Long addNewPact(PactBasicMo basicMo, Long cityCode, Long provCode) {
        //1 、订单信息查询
        ZfOrder order = orderService.getOrderByOrderId(provCode, cityCode, Long.parseLong(basicMo.getOrderId()));
        PactHouseDto house = basicService.getPactHouseInfo(order.getHouseId(),provCode,cityCode);

        ZfPact pact = new ZfPact();
        pact.setProvinceCode(provCode);
        pact.setCityCode(cityCode);
        pact.setOrderId(order.getId());
        pact.setTransactionType(order.getType());
        pact.setPactType(basicMo.getPactType());
        pact.setPactTemp(basicMo.getPactTemp());
        pact.setPactStatus(PactConstants.PactStatus.NOTACTIVE.getValue());
        pact.setAmount(order.getAmount());
        pact.setSignAgent(order.getSignAgent());
        pact.setSignName(order.getSignName());
        pact.setDeptId(order.getDeptId());
        pact.setDeptName(order.getDeptName());
        pact.setFinalPrice(order.getFinalPrice());
        pact.setPriceUnit(order.getPriceUnit());
        pact.setHouseId(order.getHouseId());
        pact.setAddress(order.getAddress());
        pact.setCreateTime(new Date());
        pact.setRegionName(house.getRegionName());
        pact.setStreetName(house.getStreetName());
        pact.setArea(house.getArea());
        pact.setCertType(house.getCertType());
        pact.setCertNumber(house.getCertNumber());
        pact.setCityName(house.getCityName());
        pact.setOwner(order.getOwnName());
        //pact.setIsDy();
       int c = baseMapper.insert(pact);
        // 添加甲方产权人信息
        List<PactPersonMo> owner = ownerCertificateService.getOwner(order.getHouseId(), provCode, cityCode);
        List<ZfPactPersonInfo> persons = PactMapper.INSTANCE.moToPersonList(owner);
        for (ZfPactPersonInfo personInfo : persons) {
            personInfo.setCityCode(cityCode);
            personInfo.setProvinceCode(provCode);
            personInfo.setPactId(pact.getId());
        }
        personInfoService.saveBatch(persons);
        return  pact.getId();
    }



    @Override
    public PactDetailDto pactDetail(Long cityCode, Long provCode, Long pactId) {
        // 1, 查询合同信息
        PactDetailDto pact = new PactDetailDto();
        PactInfoMo infoMo = this.getBasicPact(provCode, cityCode, pactId);
        pact.setInfoMo(infoMo);
        List<PactPersonDto> personMos = infoService.getPactPersons(provCode, cityCode, pactId);
        pact.setPersonMos(personMos);
        if (infoMo!=null && "1".equals(infoMo.getTransactionType())) {
            PactRentInfoMo rentInfoMo = pactRentInfoService.pactRentInfo(provCode, cityCode, pactId);
            pact.setRentInfoMo(rentInfoMo);
        }

        return pact;
    }


    @Override
    public PactInfoMo getBasicPact( Long provCode,Long cityCode,  Long pactId) {
        return baseMapper.getPactInfo(provCode, cityCode, pactId);
    }


    @Override
    public Page<PactSearchResMo> myPact(Long provCode, Long cityCode, PactSearchMo pactSearchMo) {
        Page<PactSearchResMo> page = new Page<>(pactSearchMo.getCurrent(), pactSearchMo.getPageSize());
        page.setRecords(baseMapper.searchPact(provCode, cityCode, pactSearchMo, SecurityUtils.getLoginUser().getAgentNo(),page));
        return page;
    }


    @Override
    public Map<String, Object> previewPact(Long provCode, Long cityCode, Long pactId) {
        //1、 查询基本信息
        PactInfoMo pactInfoMo =  baseMapper.getPactInfo(provCode, cityCode, pactId);
        // 获取甲乙双方信息
        List<PactPersonDto> personMos = infoService.getPactPersons(provCode, cityCode, pactId);
        Map<String, Object> map = new HashMap<>();
        if ("1".equals(pactInfoMo.getTransactionType())) {
            PactRentInfoMo rentInfo = pactRentInfoService.pactRentInfo(provCode, cityCode, pactId);
            JSONArray pa =   JSONArray.parseArray(rentInfo.getPartyA());
            JSONArray pb =   JSONArray.parseArray(rentInfo.getPartyB());
            PactTempMo pt = new PactTempMo();
            for(int i=0;i<pa.size();i++) {
                String a = pa.getString(i);
                switch (a) {
                    case "1":
                        pt.setS("1");
                        break;
                    case "2":
                        pt.setD("2");
                        break;
                    case "3":
                        pt.setK("3");
                        break;
                    case "4":
                        pt.setR("4");
                        break;
                    case "5":
                        pt.setW("5");
                        break;
                    case "6":
                        pt.setC("6");
                        break;
                }

            }
            PactTempMo pt1 = new PactTempMo();
            for(int i=0;i<pb.size();i++) {
                String b = pb.getString(i);
                switch (b) {
                    case "1":
                        pt1.setS("1");
                        break;
                    case "2":
                        pt1.setD("2");
                        break;
                    case "3":
                        pt1.setK("3");
                        break;
                    case "4":
                        pt1.setR("4");
                        break;
                    case "5":
                        pt1.setW("5");
                        break;
                    case "6":
                        pt1.setC("6");
                        break;
                }

            }
            map.put("rent", rentInfo);
            map.put("pa", pt);
            map.put("pb", pt1);
        }
        map.put("personInfos", personMos);
        map.put("pact", pactInfoMo);

    return  map;
    }

    @Override
    @Transactional
    public void pactToPdf(Long provCode, Long cityCode, Long pactId,Long orderId) {
        Map<String,Object> temp =   this.previewPact(provCode,cityCode,pactId);
        Template template = null;
        OutputStream os=null;
        try {
            template = freeMarkerConfigurer.getConfiguration().getTemplate("index.ftl");
            String resp = FreeMarkerTemplateUtils.processTemplateIntoString(template,temp);
            // 文件转换成pdf 并写入本地
            File foder = new File(upload+"/"+pactId);
            if (!foder.exists()) {
                foder.mkdirs();
            }
            String path= foder.getPath()+"/"+ RandomUtil.randomStringUpper(8) +".pdf";
             os = new FileOutputStream(path);
            pdfUtil.createPdfByHtml(os,resp);
            // 读取本地文件上传oss
           File file  =FileUtil.file(path);
            Map<String,String> map =   ossUtil.uploadObject2OSS(file,Constants.BUCKET_PACT,Constants.FOLDER_PACT+"/"+pactId);
            // 保存合同路径
            ZfPactPdf pdf = new ZfPactPdf();
            pdf.setPactId(pactId);
            pdf.setCityCode(cityCode);
            pdf.setProvinceCode(provCode);
            pdf.setPath(map.get("path"));
            pdf.setUrl(map.get("url"));
            pdf.setCreateTime(new Date());
            pdf.setType(1);
            pdf.setOrderId(orderId);
            pdfService.save(pdf);

        } catch (IOException | TemplateException | DocumentException e) {
            e.printStackTrace();
        }finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        String s= "[\"2\",\"6\"]";
        JSONArray pa = JSONArray.parseArray(s);
        for(int i=0;i<pa.size();i++) {
            System.out.println(pa.getString(i));
        }
    }
}
